package com.ge.modules.api.controller;

import com.ge.common.annotation.AuthIgnoreApi;
import com.ge.common.annotation.LoginUserApi;
import com.ge.common.utils.R;
import com.ge.modules.api.service.TbUserService;
import com.ge.common.validator.Assert;
import com.ge.modules.api.service.TbUserTokenService;
import com.ge.modules.entity.TbUser;
import com.ge.modules.entity.TbUserToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

/**
 * API授权登录
 *
 * @author wuye
 * @date 2018/2/28 10:05:43
 */
@RestController
@RequestMapping("/api/user")
public class ApiUserLoginController {
    @Autowired
    private TbUserService userService;
    @Autowired
    private TbUserTokenService tokenService;

    /**
     * 登录
     */
    @AuthIgnoreApi
    @PostMapping("/login")
    public R login(String mobile, String password) {
        System.out.println(">>>>>>>>>>>>mobile:"+mobile);
        System.out.println(">>>>>>>>>>>>password:"+password);
        Assert.isBlank(mobile, "手机号不能为空");
        Assert.isBlank(password, "密码不能为空");

        //用户登录
        Integer userId = userService.login(mobile, password);

        //生成token
        Map<String, Object> map = tokenService.createToken(userId);
        map.put("user", userService.foundById(userId));
        return R.ok().put("data",map);
    }


    @RequestMapping("/loginOut")
    public R loginOut(@LoginUserApi TbUser tbUser){
        Assert.isNull(tbUser,"用户为空");
        TbUserToken userToken = tokenService.queryByUserId(tbUser.getUserId());
        System.out.println(userToken);
        if (userToken!=null){
            tokenService.deleteToken(userToken);
            return R.ok();
        }else {
            return R.error("token不能为空");
        }
    }
}
